package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.service.IYddCateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@RestController
@RequestMapping("/ydd_cate")
public class YddCateController {
    @Autowired
    private IYddCateService iYddCateService;

    /**
     * 分页条件查询
     * @param catename
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData page(String catename,String page,String limit){
        log.info("page{},limit{}",page,limit);
        //构造分页构造器
        Page pageInfo = new Page(Integer.parseInt(page),Integer.parseInt(limit));
        //构造条件过滤
        LambdaQueryWrapper<YddCate> yddCateLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据文章标题进行模糊查询
        yddCateLambdaQueryWrapper.like(StringUtils.isNotEmpty(catename),YddCate::getCatename,catename);

        //查询
        iYddCateService.page(pageInfo,yddCateLambdaQueryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("data", pageInfo.getRecords());
        map.put("totalPages", pageInfo.getPages());
        map.put("currentPage", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        map.put("count", pageInfo.getTotal());
        return ResultData.ok("成功",map);

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData delete(int id){
        iYddCateService.removeById(id);
        return ResultData.ok("删除成功",null);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData getById(int id){
        YddCate cate = iYddCateService.getById(id);
        return ResultData.ok("回显成功",cate);
    }

    /**
     * 修改
     * @param yddCate
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddCate yddCate){
        iYddCateService.updateById(yddCate);
        return ResultData.ok("修改成功",null);
    }

    /**
     * 新增
     * @param yddCate
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddCate yddCate){
        iYddCateService.save(yddCate);
        return ResultData.ok("添加成功！",null);
    }

    /**
     * 查询所有分类
     * @return
     */
    @GetMapping("/all")
    public ResultData all(){
        List<YddCate> list = iYddCateService.list();
        return ResultData.ok("ok",list);
    }
}
